package com.lagou.rpcclient.lagou.handler;

import com.lagou.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * 自定义事件处理器
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter
		implements Callable<String> {

	private ChannelHandlerContext context;

	private RpcRequest rpcRequest;

	private String result;

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		this.context = ctx;
	}

	@Override
	public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof RpcRequest) {
			result = ((RpcRequest) msg).getResult();
		}
		notifyAll();
	}

	@Override
	public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
		super.channelWritabilityChanged(ctx);
	}

	@Override
	public synchronized String call() throws Exception {
		context.writeAndFlush(rpcRequest);
		wait();
		return result;
	}

	public void setRpcRequest(RpcRequest rpcRequest) {
		this.rpcRequest = rpcRequest;
	}
}
